import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';

export async function GET() {
  try {
    // 获取新闻统计
    const newsStats = await db.get<any>(`
      SELECT 
        COUNT(*) as total,
        SUM(is_published) as published,
        SUM(view_count) as totalViews
      FROM news
    `);

    // 获取成员统计
    const memberStats = await db.get<any>(`
      SELECT 
        COUNT(*) as total,
        SUM(is_active) as active
      FROM members
    `);

    // 获取最近发布的新闻
    const recentNews = await db.all<any>(`
      SELECT title, created_at as createdAt, author
      FROM news 
      WHERE is_published = 1
      ORDER BY created_at DESC 
      LIMIT 5
    `);

    // 构建统计数据
    const stats = {
      totalNews: newsStats?.total || 0,
      publishedNews: newsStats?.published || 0,
      totalViews: newsStats?.totalViews || 0,
      totalMembers: memberStats?.total || 0,
      activeMembers: memberStats?.active || 0
    };

    // 构建最近活动
    const recentActivities = recentNews.map((news: any, index: number) => ({
      id: `news-${index}`,
      type: 'news',
      title: '发布新闻',
      description: news.title,
      timestamp: formatTimestamp(news.createdAt),
      user: news.author
    }));

    return NextResponse.json({
      success: true,
      data: {
        stats,
        recentActivities
      }
    });
  } catch (error) {
    console.error('Error fetching stats:', error);
    return NextResponse.json({
      success: false,
      error: 'Failed to fetch stats'
    }, { status: 500 });
  }
}

function formatTimestamp(timestamp: string): string {
  const now = new Date();
  const date = new Date(timestamp);
  const diffMs = now.getTime() - date.getTime();
  const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
  const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));

  if (diffHours < 1) return '刚刚';
  if (diffHours < 24) return `${diffHours}小时前`;
  if (diffDays < 30) return `${diffDays}天前`;
  return date.toLocaleDateString('zh-CN');
}